using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;

namespace SupplierOpenApi.Controllers
{
    [Route("supplier-openapi/token")]
    [ApiController]
    public class TokenController : ControllerBase
    {
        private readonly string _secretKey = "yourSecretKey"; // 替换为你的密钥

        [HttpPost("create.lf")]
        public IActionResult CreateToken([FromQuery] string appkey, [FromQuery] string appsecret)
        {
            // 验证appkey和appsecret
            if (string.IsNullOrEmpty(appkey) || string.IsNullOrEmpty(appsecret))
            {
                return BadRequest(new
                {
                    errorTrace = "Appkey or Appsecret is missing.",
                    errorCode = 400,
                    prompt = "Appkey and Appsecret are required.",
                    success = false,
                    data = (object)null
                });
            }

            // 这里可以添加对appkey和appsecret的验证逻辑
            // 例如，检查它们是否与数据库中存储的值匹配
            if (appkey != "IN2GvivxLR4nel" || appsecret != "ktFBu91tCtrVf3ocmbEZbfKG4")
            {
                return Unauthorized(new
                {
                    errorTrace = "Invalid Appkey or Appsecret.",
                    errorCode = 401,
                    prompt = "Invalid credentials.",
                    success = false,
                    data = (object)null
                });
            }

            // 创建token
            var token = GenerateJwtToken(appkey);

            return Ok(new
            {
                errorTrace = (string)null,
                errorCode = (int?)null,
                prompt = (string)null,
                success = true,
                data = new
                {
                    accessToken = token,
                    expiresIn = 86400 // 24小时
                }
            });
        }

        private string GenerateJwtToken(string appkey)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_secretKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, appkey)
                }),
                Expires = DateTime.UtcNow.AddHours(24), // 24小时有效期
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }
    }
}